<?php
/*
 * @Descripttion: 接口-用户类
 * @Author: DanceLynx
 * @Date: 2020-11-16 23:06:51
 * @LastEditors: DanceLynx
 * @LastEditTime: 2020-11-17 14:15:56
 */
namespace addons\sdcmenu\controller\api;

use addons\sdcmenu\model\Third;
use think\Cache;
use think\Validate;

class User extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['register','login'];

    /**
     * @description: 用户登录
     * @param string username 用户名
     * @param string password 密码
     * @return array response 用户信息或错误信息
     */
    public function login()
    {
        if(! $this->request->isPost()){
            $this->error(__('Request method falied'));
        }
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        if(!$username || !$password){
            $this->error(__('Params invaled'));
        }
        $result = $this->auth->login($username,$password);
        if(! $result){
            $this->error($this->auth->getError());
        }
        $this->success(__('Logined successful'),$this->auth->getUserinfo());
    }

    /**
     * @description: 用户注册
     * @param string username 用户名
     * @param string password 密码
     * @param string mobile 手机号
     * @param string captcha 用户验证码
     * @param string captcha_key 缓存验证码key
     * @return array response 用户信息或错误信息
     */
    public function register()
    {
        if(! $this->request->isPost()){
            $this->error(__('Request method falied'));
        }
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $captcha_key = $this->request->post('captcha_key');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if(!Validate::checkRule($captcha,'require|length:4')){
            $this->error(__('captcha must required'));
        }
        if(!Validate::checkRule($captcha_key,'require')){
            $this->error(__('captcha key must required'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        // 缓存中取出验证码进行比对
        if(strtolower(Cache::pull($captcha_key)) != strtolower($captcha)){
            $this->error(__('captcha failed'));
        }
        $ret = $this->auth->register($username, $password, '', $mobile, []);
        if (!$ret) {
            $this->error($this->auth->getError());
        }
        $data = ['userinfo' => $this->auth->getUserinfo()];
        // 写入第三方用户表
        $userValues = [
            'user_id' => $data['userinfo']['user_id'],
            'platform' => 'register',
            'openname' => $username
        ];
        $third = new Third();
        $third->save($userValues);
        $this->success(__('Sign up successful'), $data);
    }
}